declare namespace g = "ddi:group:3_1";
declare namespace dc="ddi:dcelements:3_1";
declare namespace d="ddi:datacollection:3_1"; 
declare namespace dc2="http://purl.org/dc/elements/1.1/"; 
declare namespace s="ddi:studyunit:3_1"; 
declare namespace c="ddi:conceptualcomponent:3_1";
declare namespace r="ddi:reusable:3_1"; 
declare namespace a="ddi:archive:3_1"; 
declare namespace ddi="ddi:instance:3_1"; 
declare namespace l="ddi:logicalproduct:3_1";

import module namespace request="http://exist-db.org/xquery/request";
import module namespace json="http://www.json.org";

(: if callback is defined :)
let $callback := request:get-parameter("callback", ())
let $lang := request:get-parameter("lang", ())

let $s := request:get-parameter("s", ("mamma"))
let $series := request:get-parameter("series", ())

let $start := xs:integer(request:get-parameter("start", "0"))
let $records := xs:integer(request:get-parameter("records", "10"))
let $action := request:get-parameter("action","search")

let $collection := collection('/db/ddi3/internal')

let $collection := if(empty($series)) 
    then
        $collection
    else
        $collection/ddi:DDIInstance/s:StudyUnit[r:UserID[@type='series_id'] = $series]

let $result :=
    if(empty($lang))
    then
        $collection//s:StudyUnit/r:Citation[ft:query(r:Title, $s) or ft:query(..//r:Content, $s) or ft:query(..//d:QuestionText, $s) or ft:query(r:Creator, $s)]
    else
        $collection//d:QuestionItem[ft:query(d:QuestionText[@xml:lang=$lang], $s)]


return
    <hit>{$result}</hit>